package group.igfd.manager.biz.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import group.igfd.manager.biz.entity.*;
import group.igfd.manager.biz.service.*;
import group.igfd.manager.biz.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * buyer发布表
 *
 * @author knight
 * @email sunlightcs@gmail.com
 * @date 2018-10-18 13:13:51
 */
@RestController
@RequestMapping("biz/publishCustomers")
@Api(tags = {"A004/ 客人发布商品管理"})
public class PublishCustomersController {
    @Autowired
    private PublishCustomersService publishCustomersService;

    private Logger logger = LoggerFactory.getLogger( PublishCustomersController.class);

    @Autowired
    private PicturesService picturesService;

    @Autowired
    private BrandsService brandsService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private CategoriesService categoriesService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    private ReviewReasonService reviewReasonService;
    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("biz:publishCustomers:list")
    @ApiOperation(value = "列表")
    public R list(@RequestParam Map<String, Object> params){
        logger.info("biz:publishbuyers:list=== params:[{}]", JSON.toJSONString(params));
        PageUtils page = publishCustomersService.queryPage(params);

        return R.ok().put("page", page);
    }

    @GetMapping("/getItem")
    @RequiresPermissions("biz:publishCustomers:list")
    @ApiOperation(value = "根据id获取客人发布商品")
    public R getGoodsById(@RequestParam Integer id) {
        Map<String, Object> resultMap = new HashMap<>();

        EntityWrapper<PublishCustomersEntity> publishCustomersEntityEntityWrapper = new EntityWrapper<>();
        publishCustomersEntityEntityWrapper.eq("id",id);
        PublishCustomersEntity publishCustomersEntity = publishCustomersService.selectOne(publishCustomersEntityEntityWrapper);

        //图片信息
        EntityWrapper<PicturesEntity> picturesEntityEntityWrapper = new EntityWrapper<>();
        picturesEntityEntityWrapper.eq("parent_id",id);
        picturesEntityEntityWrapper.eq("type","customer_post");
        List<PicturesEntity> picturesEntities = picturesService.selectList(picturesEntityEntityWrapper);

        List<Map<String, String>> maps = new ArrayList<>();
        for (PicturesEntity picturesEntity:picturesEntities) {
            if ("image".equals(picturesEntity.getFileType())) {
                Map<String, String> pictureData = new HashMap<>();
                pictureData.put("imsrc",picturesEntity.getUrl());
                maps.add(pictureData);
            } else if ("video".equals(picturesEntity.getFileType())){
                Map<String, String> videoData = new HashMap<>();
                videoData.put("videosrc",picturesEntity.getUrl());
                maps.add(videoData);
            }
        }
        resultMap.put("files",maps);

        //标题
        resultMap.put("title",publishCustomersEntity.getTitle());
        //品牌
        if (brandsIsExist(publishCustomersEntity.getBrand()) == false) {
            resultMap.put("brandFlag",1);
        } else {
            resultMap.put("brandFlag",0);
        }
        if (StringUtils.isNumeric(publishCustomersEntity.getBrand())) {
            EntityWrapper<BrandsEntity> brandsEntityEntityWrapper = new EntityWrapper<>();
            brandsEntityEntityWrapper.eq("id",publishCustomersEntity.getBrand());
            BrandsEntity brandsEntity = brandsService.selectOne(brandsEntityEntityWrapper);
            if (brandsEntity != null) {
                resultMap.put("brand",brandsEntity.getName());
            } else {
                resultMap.put("brand",publishCustomersEntity.getBrand());
            }
        } else {
            resultMap.put("brand",publishCustomersEntity.getBrand());
        }
        //分类
        if (StringUtils.isNumeric(publishCustomersEntity.getType())) {
            EntityWrapper<CategoriesEntity> categoriesEntityEntityWrapper = new EntityWrapper<>();
            categoriesEntityEntityWrapper.eq("id",publishCustomersEntity.getType());
            CategoriesEntity categoriesEntity = categoriesService.selectOne(categoriesEntityEntityWrapper);

            if (categoriesEntity != null) {
                resultMap.put("category",categoriesEntity.getName());
            } else {
                resultMap.put("category","");
            }
        } else {
            resultMap.put("category",publishCustomersEntity.getType());
        }

        return R.ok().put("data", resultMap);
    }

    @GetMapping("/getCustomerInfo")
    @ApiOperation(value = "根据id获取客人发布商品")
    public R getGoodsByIdQuotes(@RequestParam Integer id) {

        Map<String, Object> resultMap = new HashMap<>();

        EntityWrapper<PublishCustomersEntity> publishCustomersEntityEntityWrapper = new EntityWrapper<>();
        publishCustomersEntityEntityWrapper.eq("id",id);
        PublishCustomersEntity publishCustomersEntity = publishCustomersService.selectOne(publishCustomersEntityEntityWrapper);

        //图片信息
        EntityWrapper<PicturesEntity> picturesEntityEntityWrapper = new EntityWrapper<>();
        picturesEntityEntityWrapper.eq("parent_id",id);
        picturesEntityEntityWrapper.eq("type","customer_post");
        List<PicturesEntity> picturesEntities = picturesService.selectList(picturesEntityEntityWrapper);
        List<Map> imagesList = new ArrayList<>();
        for (PicturesEntity picturesEntity:picturesEntities) {
            Map<String, String> imageInfo = new HashMap<>();

            if ("image".equals(picturesEntity.getFileType())) {
                imageInfo.put("src",picturesEntity.getUrl());
            } else if ("video".equals(picturesEntity.getFileType())){
                imageInfo.put("src",picturesEntity.getFirstImage());
            }
            imagesList.add(imageInfo);
        }
        resultMap.put("imageList",imagesList);
        resultMap.put("brand",publishCustomersEntity.getBrand());

        CategoriesEntity categoriesEntity = categoriesService.selectById(publishCustomersEntity.getType());
        if (categoriesEntity != null) {
            if (categoriesEntity.getFatherId() != 0) {
                resultMap.put("category2",categoriesEntity.getId());
                resultMap.put("category1",categoriesEntity.getFatherId());
            } else {
                resultMap.put("category1",categoriesEntity.getId());
                resultMap.put("category2","");
            }
        } else {
            resultMap.put("category1",publishCustomersEntity.getType());
            resultMap.put("category2","");
        }

        resultMap.put("sex",publishCustomersEntity.getSex());
        resultMap.put("sku",publishCustomersEntity.getSku());
        resultMap.put("color",publishCustomersEntity.getColor());
        resultMap.put("size",publishCustomersEntity.getSize());

        return R.ok().put("data", resultMap);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("biz:publishCustomers:info")
    public R info(@PathVariable("id") Integer id){
			PublishCustomersEntity publishCustomers = publishCustomersService.selectById(id);

        return R.ok().put("publishCustomers", publishCustomers);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("biz:publishCustomers:save")
    public R save(@RequestBody PublishCustomersEntity publishCustomers){
			publishCustomersService.insert(publishCustomers);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("biz:publishCustomers:update")
    public R update(@RequestBody PublishCustomersEntity publishCustomers){
			publishCustomersService.updateById(publishCustomers);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("biz:publishCustomers:delete")
    public R delete(@RequestBody Integer[] ids){
			publishCustomersService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 审核
     * */
    @RequestMapping("/auth/{id}")
    @RequiresPermissions("biz:publishCustomers:auth")
    public R auth(@PathVariable("id") Integer id,@RequestParam(defaultValue = "1") Integer state,
                  @RequestParam(required = false) String reason){
        logger.info(id.getClass().toString());
        ReviewReasonEntity reviewReasonEntity = null;
        if (state == 2) {
            reviewReasonEntity = new ReviewReasonEntity();

            reviewReasonEntity.setParentId(id);
            reviewReasonEntity.setType(0);
            reviewReasonEntity.setReason(reason);
            reviewReasonEntity.setCreatedAt(new Date());
            reviewReasonEntity.setUpdatedAt(new Date());

            reviewReasonService.insert(reviewReasonEntity);
        }

        PublishCustomersEntity brands = publishCustomersService.selectById(id);

        //判断是否添加新的品牌
        boolean isExist = brandsIsExist(brands.getBrand());
        BrandsEntity brandsEntity = null;
        if (isExist == false && state == 1) {
            brandsEntity = new BrandsEntity();

            brandsEntity.setName(brands.getBrand().toUpperCase());
            brandsEntity.setCreatedAt(new Date());
            brandsEntity.setUpdatedAt(new Date());
            brandsEntity.setSearchIndex(0);
            brandsEntity.setAuthFlag(1);
            brandsEntity.setDelFlag(0);
            brandsEntity.setFix(getSearchFirstLetter(brandsEntity.getName()));

            brandsService.insert(brandsEntity);
        }

        brands.setFlag(state);
        if (state == 2 && reviewReasonEntity != null) {
            brands.setReasonId(reviewReasonEntity.getId());
        }
        if (isExist == false && brandsEntity != null) {
            brands.setBrand(String.valueOf(brandsEntity.getId()));
        }
        boolean updateFlag = publishCustomersService.updateById(brands);

        //审核通过的短信
        if (updateFlag && state == 1) {
            EntityWrapper<UsersEntity> usersEntityEntityWrapper = new EntityWrapper<>();
            usersEntityEntityWrapper.eq("uid",brands.getUid());
            UsersEntity usersEntity = usersService.selectOne(usersEntityEntityWrapper);

            if (usersEntity != null) {
                smsService.sendPublishCheckRemind(usersEntity.getUsername(),brands.getTitle());
            }
        }
        return R.ok();
    }

    @PostMapping("/quotes/{id}")
    public R buyerQuotes(@PathVariable("id") Integer id,@RequestParam String brandId,
                         @RequestParam String categoryId,@RequestParam String sex,
                         @RequestParam String sku,@RequestParam String color,
                         @RequestParam String size,@RequestParam String eurPrice,
                         @RequestParam String discount,@RequestParam String arrivalTime,
                         @RequestParam String buyerUid) {
        String resultFlag = "fail";

        //1.先获取发布商品
        PublishCustomersEntity publishCustomersEntity = publishCustomersService.selectById(id);
        if (publishCustomersEntity != null) {

            //更新原来客人发布的商品信息
            publishCustomersEntity.setBrand(brandId);
            publishCustomersEntity.setType(categoryId);
            publishCustomersEntity.setSex(sex);
            publishCustomersEntity.setSku(sku);
            publishCustomersEntity.setColor(color);
            publishCustomersEntity.setSize(size);

            //创建报价信息
            QuotesEntity quotesEntity = new QuotesEntity();

            quotesEntity.setUid(buyerUid);
            quotesEntity.setPid(String.valueOf(id));
            quotesEntity.setPrice(eurPrice);
            quotesEntity.setDays(arrivalTime);
            quotesEntity.setStatus(1);
            quotesEntity.setCreatedAt(DateUtil.getTime());
            quotesEntity.setUpdatedAt(DateUtil.getTime());
            quotesEntity.setPublishUid(publishCustomersEntity.getUid());
            quotesEntity.setCurrency("EUR");
            quotesEntity.setRebate(new BigDecimal(Integer.valueOf(discount) / 100.0));

            boolean b = publishCustomersService.toCustomerGoodsQuotes(publishCustomersEntity, quotesEntity);
            if (b) {
                resultFlag = "success";
            }
        }

        return R.ok().put("data",resultFlag);
    }

    private boolean brandsIsExist(String brand) {
        boolean resultFlag = true;

        if (StringUtils.isNumeric(brand)) {
            BrandsEntity brandsEntity = brandsService.selectById(brand);
            if (brandsEntity == null) {
                resultFlag = false;
            }
        } else {
            resultFlag = false;
        }

        return resultFlag;
    }

    private String getSearchFirstLetter(String str) {
        //1.先获取第一个字
        String[] split = str.split("");

        String reg = "[\\u4e00-\\u9fa5]+";
        boolean result1 = split[0].matches(reg);
        if (result1) {
            //为汉字
            return getFirstLetter(split[0]);
        } else {
            //字母或数字字符串
            return split[0];
        }
    }

    /**
     * 取第一个汉字的第一个字符
     * @Title: getFirstLetter
     * @Description: TODO
     * @return String
     * @throws
     */
    public static String getFirstLetter(String ChineseLanguage){
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 输出拼音全部大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            String str = String.valueOf(cl_chars[0]);
            if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                hanyupinyin = PinyinHelper.toHanyuPinyinStringArray(
                cl_chars[0], defaultFormat)[0].substring(0, 1);;
            } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                hanyupinyin += cl_chars[0];
            } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母

                hanyupinyin += cl_chars[0];
            } else {// 否则不转换

            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }

}
